package bid

import (
	"errors"
	"wx-api/adx-bid/cache"
	"wx-api/adx-bid/model/m_adxapp"
	"wx-api/adx-bid/model/m_adxlist"
	"wx-api/adx-bid/model/m_adxslot"
	"wx-api/adx-bid/model/m_dsp_adv_creative"
	"wx-api/adx-bid/models/bid/BidModel"
	"wx-api/adx-bid/services/common"
	"wx-api/adx-bid/utils"
)

func DspRtbAd(isdebug bool, sty string, req *BidModel.BidRequest, a_info *m_adxlist.AdxList, m_info *m_adxapp.AdxApp, s_info *m_adxslot.AdxSlot) (*BidModel.BidResponse, string, string, string, error) {
	//获取广告位对应的计划
	plan_arr := cache.GetRunDspAdvPlanSlotMap(a_info.Uqid + s_info.Uqid)
	if len(plan_arr) == 0 {
		//无媒体定向，查询通投计划
		plan_arr = cache.GetRunDspAdvPlanSlotMap("all")
	}
	common.PriMsg(isdebug, "plan_arr:", plan_arr)
	//广告筛选
	ad_arrs := []*m_dsp_adv_creative.DspAdvCreative{}
	ad_arrs_ids := []string{}
	max_price := float64(0)
	for _, s := range plan_arr {
		plan_info, ok := cache.CacheDspAdvPlanMapGet(s)
		if !ok || plan_info == nil {
			common.PriMsg(isdebug, "pppp:", s)
			continue
		}
		tmp_info, ok := DspRtbAdSeach(isdebug, req, plan_info)
		if !ok || tmp_info == nil {
			common.PriMsg(isdebug, "aaaaa:", s)
			continue
		}
		if tmp_info.Price > max_price {
			max_price = tmp_info.Price
		}
		ad_arrs = append(ad_arrs, tmp_info)
		ad_arrs_ids = append(ad_arrs_ids, tmp_info.Uqid)
	}
	common.PriMsg(isdebug, "max_price:", max_price)
	common.PriMsg(isdebug, "ad_arrs:", ad_arrs_ids)
	//竞价范围,70%涵盖
	ad_arr := []*m_dsp_adv_creative.DspAdvCreative{}
	for _, s := range ad_arrs {
		if s.Price >= (max_price * 0.7) {
			ad_arr = append(ad_arr, s)
		}
	}
	if len(ad_arr) == 0 {
		return nil, "", "", "", errors.New("dsp no ad")
	}

	//随机抽选一个
	ad_info_num := utils.RandInt64(0, int64(len(ad_arr)-1))
	ad_info := ad_arr[ad_info_num]
	if ad_info == nil {
		return nil, "", "", "", errors.New("dsp no adinfo")
	}

	plan_info, _ := cache.CacheDspAdvPlanMapGet(ad_info.PlanId)
	res_bid := &BidModel.BidResponse_SeatBid_Bid{
		Id: "1",
	}

	DoAdm(req, res_bid, plan_info, ad_info)

	//上报链接生成
	GetDspTrackUrls(req, res_bid, sty, a_info.Uqid, m_info.Uqid, s_info.Uqid, plan_info, ad_info)

	res := &BidModel.BidResponse{
		Id:    req.GetId(),
		Bidid: utils.GetUUid(),
		Seatbid: []*BidModel.BidResponse_SeatBid{
			{
				Bid: []*BidModel.BidResponse_SeatBid_Bid{
					res_bid,
				},
			},
		},
	}
	return res, plan_info.AdvId, ad_info.PlanId, ad_info.Uqid, nil
}
